package com.deli.service.impl;

import com.deli.entity.TestUserList;
import com.deli.mapper.TestUserListMapper;
import com.deli.service.TestUserListService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

@Service("testUserListService")
@Transactional
public class TestUserListServiceImpl implements TestUserListService {
    @Autowired
    private TestUserListMapper testUserListMapper;

    @Override
    public String selectQuestionByStartID(int startId) {
        return null;
    }

    /**
     * 查询是否有答题权限
     *
     * @param userName 用户名（本名或者花名）
     * @param phoneNum 电话号码
     * @return status
     * @throws Exception
     */
    @Override
    public List<LinkedHashMap<String, Object>> getStatusAndTestTypeByNameAndPhone(String userName, String phoneNum) throws Exception {
        List<LinkedHashMap<String, Object>> status = testUserListMapper.getStatusAndTestTypeByNameAndPhone(userName, phoneNum);
        if (status == null || status.size() < 1) {
            throw new Exception("您无需进行测评。测评可向HR申请");
        }
        return status;
    }

    /**
     * 更新状态
     *
     * @param userName
     * @param phoneNum
     * @param testType
     * @param status
     * @return
     * @throws Exception
     */
    @Override
    public Integer updateStatusByUserNameAndPhoneNum(String userName, String phoneNum, Integer testType, int status) throws Exception {
        Integer update = testUserListMapper.updateStatusByUserNameAndPhoneNum(userName, phoneNum, testType, status);
        if (update != 1) {
            throw new Exception("在添加结果记录时，更新名单表状态时发生异常");
        }
        return update;
    }

    /**
     * 新增用户
     *
     * @param userName       用户名
     * @param mobilePhone    手机号
     * @param departmentname 末级部门名
     * @param testType       测试类型
     * @param userPosition   用户岗位
     * @param textfield      花名
     * @return
     */
    @Override
    public Integer addUser(String userName, String mobilePhone, String departmentname, Integer testType, String userPosition, String textfield) throws Exception {

        TestUserList testUserList = new TestUserList();
        testUserList.setDepartmentname(departmentname);
        testUserList.setMobilePhone(mobilePhone);
        testUserList.setUserName(userName);
        testUserList.setStatus(0);
        testUserList.setTextfield(textfield);
        testUserList.setUserPosition(userPosition);
        testUserList.setTestType(testType);
        //判断是否有重复的,
        Integer count = testUserListMapper.checkRepeat(testUserList);
        if (count >= 1) {
            throw new Exception("新增测评名单---判重:数据已存在");
        }
        count = testUserListMapper.addUser(testUserList);

        if (count != 1) {
            throw new Exception("新增测评名单：userName是：" + userName + "mobilePhone是：" + mobilePhone);
        }
        return count;
    }

    @Override
    public List<LinkedHashMap<String, Object>> getStatusAndTestTypeByNameAndPhoneAndTestType(String userName, String phoneNum, Integer testType) throws Exception {
        List<LinkedHashMap<String, Object>> dataList = testUserListMapper.getStatusAndTestTypeByNameAndPhoneAndTestType(userName, phoneNum, testType);
        if (dataList == null || dataList.size() < 1) {
            throw new Exception("您无需进行测评。测评可向HR申请");
        }
        return dataList;
    }

    /**
     * 用户列表条件查询
     *
     * @param userName
     * @param mobilePhone
     * @param departmentname
     * @param testType
     * @param userPosition
     * @param textfield
     * @param pageNum
     * @return
     * @throws Exception
     */
    @Override
    public List<LinkedHashMap<String, Object>> getList(String userName, String mobilePhone,
                                                       String departmentname, Integer testType,
                                                       String userPosition, String textfield,
                                                       Integer pageNum) throws Exception {
        pageNum = Integer.valueOf((pageNum - 1) * 10);
        List<LinkedHashMap<String, Object>> dataList = testUserListMapper.getList(userName, mobilePhone, departmentname, testType, userPosition, textfield, pageNum);
        if (dataList == null || dataList.size() < 1) {
            throw new Exception("查询不到用户记录");
        }

        return dataList;
    }

    @Override
    public int getUserCount() throws Exception {
        Integer count = testUserListMapper.getUserCount();
        if (count < 1) {
            throw new Exception("查询不到人员记录");
        }
        return count;
    }

    /**
     * 批量导入用户
     *
     * @param fileName 文件名
     * @param file     文件
     * @return
     */
    @Override
    public HashMap<String, Object> batchImport(String fileName, MultipartFile file) throws Exception {
        HashMap<String, Object> resultMap = new HashMap<>();
        Boolean success = false;
        List<TestUserList> userList = new ArrayList<TestUserList>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new Exception("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if (sheet != null) {
            success = true;
        }
        TestUserList testUserList;
        int count = 0;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                count++;
                continue;
            }

            testUserList = new TestUserList();
            if(count==5){
                continue;
            }
            Cell cell = row.getCell(0);
            if (cell==null||cell.equals("")||cell.getCellType() == Cell.CELL_TYPE_BLANK) {
                throw new Exception("导入失败(第" + (r + 1) + "行,数据为空)");
                //continue;
            }
            if (row.getCell(0).getCellType() != 1) {
                throw new Exception("导入失败(第" + (r + 1) + "行,姓名请设为文本格式)");
            }
            String userName = row.getCell(0).getStringCellValue();//第一列,姓名
            //名字 手机 测评类型不为空
            if (userName == null || userName.isEmpty()) {
                throw new Exception("导入失败(第" + (r + 1) + "行,姓名未填写)");
            }
            testUserList.setUserName(userName); //注入姓名

            String textfield = row.getCell(1).getStringCellValue();//第二列花名
            if (StringUtils.isNotBlank(textfield)) {
                testUserList.setTextfield(textfield);//注入花名
            }
            String departmentname = row.getCell(2).getStringCellValue();//第三列部门
            if (StringUtils.isNotBlank(departmentname)) {
                testUserList.setDepartmentname(departmentname);//注入部门
            }
            String userPosition = row.getCell(3).getStringCellValue();//第四列岗位
            if (StringUtils.isNotBlank(userPosition)) {
                testUserList.setUserPosition(userPosition);//注入岗位
            }

            row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
            String mobilePhone = row.getCell(4).getStringCellValue();//第五列手机号
            if (mobilePhone == null || mobilePhone.isEmpty()) {
                throw new Exception("导入失败(第" + (r + 1) + "行,手机号未填写)");
            }
            testUserList.setMobilePhone(mobilePhone);//手机号

            row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
            String testType = row.getCell(5).getStringCellValue();//第六列测评类型
            if (testType == null || testType.isEmpty()) {
                throw new Exception("导入失败(第" + (r + 1) + "行,测评类型未填写)");
            }
            testUserList.setTestType(Integer.parseInt(testType));//测评类型
            userList.add(testUserList);
        }
        int repeat = 0;
        for (TestUserList userResord : userList) {
            String userName = userResord.getUserName();
            String mobilePhone = userResord.getMobilePhone();
            Integer testType = userResord.getTestType();
            int cnt = testUserListMapper.selectByNameAndPhoneAndTesttypeWithStatus(userName, mobilePhone, testType);
            if (cnt == 0) {
                testUserListMapper.addUser(userResord);
                System.out.println(" 插入 " + userResord);
            } else {
                repeat++;
            }
        }
        resultMap.put("success", success);
        resultMap.put("repeat", repeat);
        return resultMap;
    }
}
